package com.android.jay.lib_pullalive.app;

import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import android.util.Log;

import androidx.annotation.RequiresApi;

/**
 * Created by wzp on 2020/2/4 0004.
 * <p>
 * 描述  ：轻量级的后台job service 利用空闲时间执行一些小事情 提高不被回收打概率
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class AliveJobService extends JobService {
    private static final String TAG = AliveJobService.class.getName();

    private JobScheduler mJobScheduler;
    private static final int PULL_ALIVE = 0X01;

    public static void start(Context activity) {
        Intent intent = new Intent(activity, AliveJobService.class);
        activity.startService(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        JobInfo job = initJobInfo(startId);
        //提交自己应用的job 到system Process
        if (mJobScheduler.schedule(job) <= 0) {
            Log.e(TAG, "AliveJobService failed");
        } else {
            Log.e(TAG, "AliveJobService successed");
        }
        //在被系统回收的时候 在合适的时候重启 所以用粘性 启动
        return START_STICKY;
    }

    //初始化 jobinfo

    private JobInfo initJobInfo(int startId) {
        JobInfo.Builder builder = new JobInfo.Builder(startId,
                new ComponentName(getPackageName(), AliveJobService.class.getName()));
        //版本兼容
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 执行条件
            // 最小延迟
            builder.setMinimumLatency(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
                    //最终执行时间
                    .setOverrideDeadline(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS)
                    //线性重试方案
                    .setBackoffCriteria(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS, JobInfo.BACKOFF_POLICY_LINEAR);
        } else {
            //最小执行间隔
            builder.setPeriodic(JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS);
        }
        builder.setPersisted(false); //是否持久化
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_NONE);//设置网络条件
        builder.setRequiresCharging(false); //是否需要充电
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder.setRequiresBatteryNotLow(true); //低电量
        }
        return builder.build();
    }

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PULL_ALIVE:
                    Log.d(TAG, "PULL ALIVE");
                    /**
                     * 第二个参数是否要重新调度
                     * **/
                    jobFinished((JobParameters) msg.obj, true);
                    break;
            }
        }
    };

    @Override
    public boolean onStartJob(JobParameters params) {
        mHandler.sendMessage(Message.obtain(mHandler, PULL_ALIVE,params));
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        mHandler.removeCallbacksAndMessages(null);
        return false;
    }
}
